<script setup lang="tsx">
import { computed, onMounted, reactive, ref } from 'vue';
import type { Ref } from 'vue';
import { TableDataWithIndex, useBoolean } from '@sa/hooks';
import { fetchGetAllPages, fetchGetMenuList } from '@/service/api';
import { $t } from '@/locales';
import { yesOrNoRecord } from '@/constants/common';
import SvgIcon from '@/components/custom/svg-icon.vue';
import MenuOperateModal, { type OperateType } from './modules/menu-operate-modal.vue';
import { ApiMenuItem, ApiMenuQuery, ApiMenuRouteOut, ApimenuserviceApi, PgType } from '@/api-services';
import { feature, getAPI } from '@/axios-utils';
import { fetchTableQuery, useNetoTable, useTableScroll } from '@/hooks/common/neto-table';
import { queryDone } from '@/utils/api';
import { ElButton, ElPopconfirm, ElTag } from 'element-plus';
import { NetoKit } from '@/typings/neto';

// 定义 apiFunc 为一个函数，接受参数并返回 Promise
const tableLoading = ref(false);
const tableData = reactive<ApiMenuItem[]>([])
const tableQuery = reactive<ApiMenuQuery>({
  keywords: ''
});
const column: UI.TableColumn<ApiMenuItem>[] = [
  {
    label: 'id',
    //dataIndex: 'id',
    prop: 'id',
    minWidth: 230,
  },
  {
    label: $t('page.manage.menu.menuName'),
    //dataIndex: 'name',
    prop: 'name',
    align: 'left',

    formatter: record => {

      const { i18nKey, name } = record;

      const label = i18nKey ? $t(i18nKey as App.I18n.I18nKey) : name;

      return <div style={{ minWidth: "120px" }}>{label} </div>;
    }
  },

  {
    //菜单类别
    label: $t('page.manage.menu.menuType'),
    //dataIndex: 'pgTypeStr',
    prop: 'pgTypeStr',
    minWidth: 80,
    align: 'center',
    formatter: record => {
      const { pgTypeStr } = record;
      const colorMap: Record<string, NetoKit.TagType> = {
        'Directory': 'success',
        'Menu': 'primary',
        'Controller': 'warning',
        'Action': 'danger'
      };

      const descMap: Record<string, string> = {
        'Directory': '目录',
        'Menu': '菜单',
        'Controller': '控制器',
        'Action': '方法'
      };

      const color = colorMap[pgTypeStr!];
      const desc = descMap[pgTypeStr!];
      return <ElTag type={color} >{desc}</ElTag>;
    }
  },

  {
    //创建时间
    prop: 'creationTime',
    //dataIndex: 'creationTime',
    label: $t('common.creationTime'),
    align: 'center',
    minWidth: 200
  },
  {
    //前端Key
    label: $t('page.manage.menu.routeName'),
    //dataIndex: 'urlKey',
    prop: 'urlKey',
    minWidth: 100,
    align: 'left',
  },
  {
    //前端URL
    label: $t('page.manage.menu.routePath'),
    //dataIndex: 'url',
    prop: 'url',
    minWidth: 200,
    align: 'left',
  },
  {
    //code
    label: 'code',
    //dataIndex: 'code',
    prop: 'code',
    minWidth: 100
  },

  {
    //code
    label: 'pcode',
    //dataIndex: 'menuPCode',
    prop: 'menuPCode',
    minWidth: 100
  },
  {
    //图标
    label: $t('page.manage.menu.icon'),
    //dataIndex: 'icon',
    prop: 'icon',
    minWidth: 60,
    align: 'center',
    formatter: record => {
      const { icon } = record;

      //渲染图标
      if (!icon) {
        return '';
      }

      return (<div class="flex-center" >
        <SvgIcon icon={icon} class="text-icon" />
      </div>)
    }
  },
  {
    label: $t('page.manage.common.isEnable'),
    //dataIndex: 'isEnable',
    align: 'center',
    minWidth: 80,
    formatter: record => {
      if (record.isEnable === null) {
        return '';
      }


      const label = $t(record.isEnable ? 'page.manage.common.status.enable' : 'page.manage.common.status.disable');
      const color = record.isEnable ? 'success' : 'warning'

      return <ElTag color={color}> {label} </ElTag>;
    }
  },
  {
    label: $t('page.manage.menu.hideInMenu'),
    prop: 'hideInMenu',
    //dataIndex: 'isHideMenu',
    align: 'center',
    minWidth: 80,
    formatter: record => {
      const hide: CommonType.YesOrNo = record.isHideMenu ? 'Y' : 'N';

      const ElTagMap: Record<CommonType.YesOrNo, string> = {
        Y: 'error',
        N: 'default'
      };

      const label = $t(yesOrNoRecord[hide]);

      return <ElTag color={ElTagMap[hide]}> {label} </ElTag>;
    }
  },
  {
    //顺序
    label: $t('page.manage.menu.order'),
    //dataIndex: 'sort',
    prop: 'sort',
    minWidth: 60,
    align: 'center',

  },
  {
    //备注
    label: $t('page.manage.common.remark'),
    //dataIndex: 'remark',
    prop: 'remark',
    align: 'center',
  },
  // {
  //   //创建人
  //   prop: 'creatorUserName',
  //   //dataIndex: 'creatorUserName',
  //   label: $t('common.creatorUserName'),
  //   align: 'center',
  //   minWidth: 100
  // },
  // {
  //   //修改时间
  //   prop: 'updateTime',
  //   //dataIndex: 'updateTime',
  //   label: $t('common.updateTime'),
  //   align: 'center',
  //   minWidth: 150
  // },
  // {
  //   //修改人
  //   prop: 'updateUserName',
  //   //dataIndex: 'updateUserName',
  //   label: $t('common.updateUserName'),
  //   align: 'center',
  //   minWidth: 100
  // },
  {
    prop: 'operate',
    label: $t('common.operate'),
    minWidth: 230,
    align: 'center',
    fixed: 'right',
    formatter: record => (
      <div class="flex-center gap-8px" >
        {
          record.pgType == PgType.Directory && (
            <ElButton type="primary" plain size="small" onClick={() => handleAddChildMenu(record)}>
              {$t('page.manage.menu.addChildMenu')}
            </ElButton>
          )}
        <ElButton type="primary" plain size="small" onClick={() => handleEdit(record)}>
          {$t('common.edit')}
        </ElButton>
        <ElPopconfirm title={$t('common.confirmDelete')} onConfirm={() => handleDelete(record.id!)}>
          {{
            reference: () => (
              <ElButton type="danger" plain size="small">
                {$t('common.delete')}
              </ElButton>
            )
          }}
        </ElPopconfirm>

      </div>


    )
  }
];
const queryMenuData = async () => {
  tableLoading.value = true;
  const [err, res] = await feature(getAPI(ApimenuserviceApi).getMenuTreeList(tableQuery));
  tableLoading.value = false;
  queryDone(err, () => {
    if (res?.data.data) {
      //清空tabledata的数据
      tableData.splice(0);
      tableData.push(...res.data.data);
    } else {
      window.$message?.error($t('common.failed'));
    }
    console.log(tableData)
  })
};


const operateType = ref<OperateType>('add');
const visible = ref(false);
const openModal = () => {
  visible.value = true;
};
function handleAdd() {
  operateType.value = 'add';
  openModal();
}

async function handleBatchDelete(ids: string) {
  // request
  const [err, res] = await feature(getAPI(ApimenuserviceApi)._delete(ids));
  queryDone(err, () => {
    if (res?.data.data) {
      window.$message?.success($t('common.success'));
      queryMenuData();
    } else {
      window.$message?.error($t('common.failed'));
    }
  })
}

async function handleDelete(id: number) {
  // request
  handleBatchDelete(id.toString())
}
/** the edit menu data or the parent menu data when adding a child menu */
const editingData: Ref<ApiMenuItem | null> = ref(null);

function handleEdit(item: ApiMenuItem) {
  operateType.value = 'edit';
  editingData.value = { ...item };

  openModal();
}

function handleAddChildMenu(item: ApiMenuItem) {
  operateType.value = 'addChild';

  editingData.value = { ...item };

  openModal();
}

const allPages = ref<string[]>([]);

async function getAllPages() {
  const { data: pages } = await fetchGetAllPages();
  allPages.value = pages || [];
}

function init() {
  //getAllPages();
  queryMenuData();
}
onMounted(() => {

  // init
  init();
})
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <ElCard class="sm:flex-1-hidden card-wrapper" body-class="ht50">
      <template #header>
        <div class="flex items-center justify-between">
          <p>{{ $t('page.manage.user.title') }}</p>
          <ElSpace>

            <ElButton size="small" plain type="primary" @click="handleAdd">
              <template #icon>
                <icon-ic-round-plus class="align-sub text-icon" />
              </template>
              <span class="ml-8px">{{ $t('common.add') }}</span>
            </ElButton>
            <ElButton size="small" @click="queryMenuData">
              <template #icon>
                <icon-mdi-refresh class="align-sub text-icon" :class="{ 'animate-spin': tableLoading }" />
              </template>
              <span class="ml-8px">{{ $t('common.refresh') }}</span>
            </ElButton>
          </ElSpace>
        </div>

      </template>
      <ElTable height="100%" border class="sm:h-full" :data="tableData" row-key="id">
        <ElTableColumn v-for="col in column" :key="col.prop" v-bind="col" />
      </ElTable>

      <!-- <ElTable ref="tableWrapperRef" size="small" :bordered="true" row-key="id" :data="tableData" :columns="column"
        :loading="tableLoading" class="h-full" :pagination="false" :expandIconColumnIndex="1"
        :scroll="{ x: 'max-content' }">
      </ElTable> -->
    </ElCard>
    <MenuOperateModal v-model:visible="visible" :operate-type="operateType" :row-data="editingData"
      :all-pages="allPages" @submitted="queryMenuData" />

  </div>
</template>

<style scoped></style>
